﻿using System;
using System.Runtime.Serialization;
using System.Windows.Controls;
using System.Windows.Ink;
using ThePresenter.Net.PresenterCom.Uids;
using ThePresenter.Windows.Controls;


namespace ThePresenter.Net.PresenterCom.Actions
{
	[Serializable]
	class DrawingAction : CanvasAction, ISerializable
	{
		private StrokeCollection _Added;
		private UidCollection _Removed;

		public DrawingAction(StrokeCollection Added, UidCollection Removed)
		{
			this._Added = Added;
			this._Removed = Removed;
		}

		public override void Execute(InkCanvas Target)
		{
			UidStrokesCollection IDStrokes = Target.Tag as UidStrokesCollection;

			#region Remove strokes
			if (this._Removed != null)
			{
				foreach (Uid Removed in this._Removed)
				{
					if (IDStrokes.ContainsKey(Removed))
					{
						if (Target.Strokes.Contains(IDStrokes[Removed]))
							Target.Strokes.Remove(IDStrokes[Removed]);
						IDStrokes.Remove(Removed);
					}
				}
			} 
			#endregion

			#region Add new strokes
			if (this._Added != null)
			{
				foreach (Stroke NewStroke in this._Added)
				{
					Uid StrokeUid = NewStroke.GetUid();
					IDStrokes.Add(StrokeUid, NewStroke); // TODO Fix Exception Null
				}
				Target.Strokes.Add(this._Added);
			} 
			#endregion
		}

		#region ISerializable Members

		public DrawingAction(SerializationInfo info, StreamingContext context)
		{
			this._Added = ((byte[])info.GetValue("Added", typeof(byte[]))).ToStrokes();
			this._Removed = (UidCollection)info.GetValue("Removed", typeof(UidCollection));
		}

		public void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			info.AddValue("Added", this._Added.ToBytes());
			info.AddValue("Removed", this._Removed, typeof(UidCollection));
		}

		#endregion
	}
}
